package com.dog.share.twitter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class TwitterShareManager {
	private Activity parentActivity;
	private Activity childActivity;
	private SharedPreferences prefs;
	public TwitterShareManager(Activity parentActivity,Activity childActivity) {
		this.parentActivity = parentActivity;
		this.childActivity = childActivity;
		prefs = PreferenceManager.getDefaultSharedPreferences(childActivity);
	}
	
	public void shareTweet(String message){
		if (TwitterUtils.isAuthenticated(prefs)) {
			Log.i("DREG", "CASE1");
			sendTweet(message);
		} else {
			Log.i("DREG", "CASE2");
			Intent i = new Intent(childActivity.getApplicationContext(),
					PrepareRequestTokenActivity.class);
			i.putExtra("tweet_msg", message);
			childActivity.startActivity(i);
		}
	}
	
	private void sendTweet(String tweetMessage) {
		new UpdateTwitterStatusTask(tweetMessage).execute();
	}

	private class UpdateTwitterStatusTask extends AsyncTask {
		private String tweetMessage;
		private ProgressDialog myProgressDialog;
		public UpdateTwitterStatusTask(String tweetMessage) {
			this.tweetMessage = tweetMessage;
		}

		@Override
		protected void onPreExecute() {
			myProgressDialog = ProgressDialog.show(parentActivity,
					"Please wait...", "Updating twitter ...", true);

		}

		@Override
		protected void onPostExecute(Object result) {
			myProgressDialog.dismiss();
			if (result == null) {
				Toast.makeText(parentActivity, "Twitter updated !",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(parentActivity,
						"\t\tOops !!\nYou can not share duplicate status", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		protected Object doInBackground(Object... arg0) {
			try {
				TwitterUtils.sendTweet(prefs, tweetMessage);
			} catch (Exception ex) {
				ex.printStackTrace();
				return "fail";
			}
			return null;
		}
	}
	
}
